<!--
 * @Description: 信息价维护
 * @Autor: wangwangwang
 * @Date: 2021-01-21 19:14:42
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-04-29 11:53:47
-->
<template>
  <div class="pages_content table priceMaintenance">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display: flex">
        <div>
          <div class="header_right" @click="showCardNav = !showCardNav">
            <div class="title">搜索</div>
            <div>
              <div :class="{ 'arrowTransform': !showCardNav, 'arrowTransformReturn': showCardNav}">
                <i style="margin-right: 5px" class="el-icon-arrow-down"></i>
              </div>
            </div>
          </div>
          <div v-show="showCardNav" class="hr"></div>
          <el-collapse-transition>
            <div v-show="showCardNav">
              <div class="search">
                <span style="display: inline-block;margin-bottom: 10px;">
                  <span style="margin-right: 12px">信息价期数：</span>
                  <el-input v-model="tableParam.dataPeriods" oninput="value=value.replace(/[^\d]/g,'');if(value<0)value=0;if(value>12)value=12" style="width: 120px" clearable placeholder="请输入" />
                </span>
                <span style="margin-left: 24px">
                  <span style="margin-right: 12px">登记人：</span>
                  <el-input v-model="tableParam.CreateUserName" style="width: 240px" clearable placeholder="请输入" />
                </span>
                <el-button icon="el-icon-search" size="medium" class="bottom_all" @click="(tableParam.page = 1), gettableData()">查 询</el-button>
                <el-button size="medium" class="bottom_all_two" style="margin-left: 12px" @click="init()">重 置</el-button>
              </div>
            </div>
          </el-collapse-transition>
          <div class="hr"></div>
          <!-- <div class="card scroll"> -->
          <div class="card">
            <div class="card_nav">
              <div>
                <el-button size="small" class="bottom_all" style="margin-left: 0" @click="add('添加')">
                  <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
                  添加信息价
                </el-button>
              </div>
            </div>
            <div v-loading="tableLoading" class="card_info" :style="style">
              <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="tableData" tooltip-effect="dark">
                <template v-for="(item, index2) in table">
                  <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :min-width="item.width" :fixed="item.label =='操作'?'right':false">
                    <template slot-scope="scope">
                      <span v-if="item.label == '信息价期数'">
                        {{scope.row.dataYear}}年 第{{scope.row.dataPeriods}}期
                      </span>
                      <span v-else-if="item.label == '状态'">
                        <span v-if="scope.row.enable == 0" style="color: #969799">禁用</span>
                        <span v-if="scope.row.enable == 1" style="color: #00a754">启用</span>
                      </span>
                      <div v-else-if="item.label == '操作'">
                        <el-button class="bottom_one" size="mini" @click="update(scope.row, '修改')">

                          修改
                        </el-button>
                        <el-button size="mini" class="bottom_two" @click="deldata(scope.row )">
                          <i class="icon iconfont iconicon_button_delete" style="font-size: 12px"></i>
                          删除
                        </el-button>
                      </div>
                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
          </div>
        </div>
      </el-main>
      <div class="card_bottom">
        <div class="card_bottom_left">
          <div class="top_page_totle">总共{{ total }}条</div>
          <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" :page-sizes="[10, 20, 30, 40,50,100,200,500,1000]" layout="prev,pager,sizes,next,jumper" :total="total" @size-change="sizeChange" @current-change="gettableData()"></el-pagination>
        </div>
        <div>
          <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="gettableData">刷新</el-button>
        </div>
      </div>
    </el-container>
    <el-dialog v-dialogDrag :visible.sync="addDialog" width="1180px" :close-on-click-modal="false" :before-close="resetFromDate">
      <span slot="title" class="dialog-title">{{ addDialogTitle }}</span>
      <div>
        <div class="top">
          <div>
            <span>期数：</span>
            <el-input v-model="fromDate.dataYear" class="input1" style="width: 120px;" onkeypress='return( /[\d]/.test(String.fromCharCode(event.keyCode)))'>
              <div slot="suffix" style="line-height:36px">年</div>
            </el-input>
            <el-input v-model="fromDate.dataPeriods" onblur="if(value > 12 ){value = 12}else if(value < 1 ){ value = 1}" onkeypress='return( /[\d]/.test(String.fromCharCode(event.keyCode)))' class="input2" style="width: 100px;">
              <div slot="prefix" style="line-height:36px">第</div>
              <div slot="suffix" style="line-height:36px">期</div>
            </el-input>
          </div>
          <div class="top">
            <span>生效时间：</span>
            <el-date-picker v-model="fromDate.time" value-format="yyyy-MM-dd HH:mm:ss" type="daterange" placeholder="选择日期时间" ange-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </div>
        </div>
        <div style="padding-top:20px">
          <!-- <el-button size="mini" class="bottom_all" style="margin-left: 0" @click="addline()">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
            添加行
          </el-button> -->
          <el-button size="mini" class="bottom_all" style="margin-left: 12px" @click="addColume(2)">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
            添加标号
          </el-button>
          <el-button size="mini" class="bottom_all" style="margin-left: 12px" @click="addColume(3)">
            <i class="icon iconfont iconicon_button_add" style="font-size: 12px"></i>
            添加原物料
          </el-button>
        </div>
        <div style="padding-top:15px">
          <el-table key="0" :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="lineList" tooltip-effect="dark" height="520px">
            <template v-for="(item,index2) in columnList">
              <el-table-column v-if="index2==0" :key="index2" width="120px" :label="item.itemName" align="center">
                <template slot="header">
                  <div class="xieXian">
                    <div></div>
                    <span>区域</span>
                    <span>标号</span>
                  </div>
                </template>
                <template slot-scope="scope">
                  {{scope.row.itemCode}}
                </template>
              </el-table-column>
              <el-table-column v-else-if="item.type===1" :key="index2" :label="item.itemName" :prop="item.itemName" align="center" width="160px">
                <template slot-scope="scope">
                  <el-input v-model="scope.row[item.itemName]" style="width:100%" onblur="if(value > 10000 ){ value = 10000}else if(value < 1 ){ value = 1}" onkeypress='return( /^[1-9]{1}\d\.)*$/.test(String.fromCharCode(event.keyCode)))' @input="scope.row[item.itemName]=$regExp.checkNum(scope.row[item.itemName])"></el-input>
                </template>
              </el-table-column>
              <el-table-column v-else-if="item.type===2" :key="index2" width="200px">
                <template slot="header" slot-scope="scope">
                  <el-select :ref="scope.row" v-model="item.itemName" placeholder="请选择" style="width:60%">
                    <el-option v-for="item in gradeList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                  <el-button style="margin-left:5px;" class="bottom_text" @click="deleteColumn(index2)">删除</el-button>
                </template>
                <template slot-scope="scope">
                  <el-input v-model="scope.row[item.itemName]" style="width:100%"></el-input>
                </template>
              </el-table-column>
              <el-table-column v-else-if="item.type===3" :key="index2" width="200px">
                <template slot="header" slot-scope="scope">
                  <el-input :ref="scope.row" v-model="item.itemName" style="width:60%"></el-input>
                  <el-button style="margin-left:5px;" class="bottom_text" @click="deleteColumn(index2)">删除</el-button>
                </template>
                <template slot-scope="scope">
                  <el-input v-model="scope.row[item.itemName]" style="width:100%"></el-input>
                </template>
              </el-table-column>
            </template>
            <!-- <el-table-column fixed="right" label="操作" width="120">
              <template slot-scope="scope">
                <el-button class="bottom_all" @click="deleteRow(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column> -->
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px" @click="submit1()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { TreeSelect } from 'ant-design-vue';
import mixin from "@/mixins/ICPSmixin.js";
import { getUserInfo } from "@/utils/auth"
import {
  queryPage, queryDetail, deletePrice, savePrice
} from "@/api/basicConfig/priceMaintenance.js";
import { getLists } from "@/api/basicConfig/companyStandard";
import { sortReg } from "@/common/RegExp.js";
export default {
  // components: { TreeSelect },
  mixins: [mixin],
  data() {
    var validatePass1 = (rule, value, callback) => {
      if (sortReg(value)) {
        callback();
      } else {
        callback(new Error("请输正整数序号!"));
      }
    };
    return {
      /*表格增删改查及下载接口*/
      queryPage: queryPage,
      /*表格数据*/
      table: [
        { label: "信息价期数", width: "auto", prop: "dataPeriods", status: true },
        { label: "信息价登记人", width: "120", prop: "createUserName", status: true },
        { label: "生效日期", width: "120", prop: "startTime", status: true },
        { label: "操作", width: "120", prop: "", status: true },
      ],
      pagesType: 0,
      /*添加表单数据*/
      rules: {
        code: [{ required: true, message: "请输入站点编码", trigger: "blur" },
        { validator: validatePass1, trigger: "blur", }
        ],
      },
      fromDate: {
        id: '',
        dataYear: '',
        dataPeriods: '',
        time: [],
      },
      lineList: [],
      columnLists: [
        {
          itemName: 'itemCode',
          type: 1,
        },
        {
          itemName: 'C10',
          type: 1,
        },
        {
          itemName: 'C15',
          type: 1,
        },
        {
          itemName: 'C20',
          type: 1,
        },
        {
          itemName: 'C25',
          type: 1,
        },
        {
          itemName: 'C30',
          type: 1,
        },
        {
          itemName: 'C35',
          type: 1,
        },
        {
          itemName: 'C40',
          type: 1,
        },
        {
          itemName: 'C45',
          type: 1,
        },
        {
          itemName: 'C50',
          type: 1,
        },
        {
          itemName: 'C55',
          type: 1,
        },
        {
          itemName: 'C60',
          type: 1,
        },
        {
          itemName: 'C65',
          type: 1,
        },
        {
          itemName: 'C70',
          type: 1,
        },
        {
          itemName: 'C75',
          type: 1,
        },
        {
          itemName: 'C80',
          type: 1,
        },
      ],
      columnList: [],
      defaultGrade: ['C10', 'C15', 'C20', 'C25', 'C30', 'C35', 'C40', 'C45', 'C50', 'C55', 'C60', 'C65', 'C70', 'C75', 'C80'],
      gradeList: [],
      TreeSelectStypeNumber: 0,
      selectRow: "",
      nameArr: ['成都市区', '天府新区', '崇州市', '大邑县', '都江堰市', '金堂县', '龙泉驿区', '彭州市', '郫都区', '蒲江县', '青白江区', '邛崃市', '双流区', '温江区', '新都区', '新津区', '简阳市', '东部新区'],
    };
  },
  created() {
    /*存储拷贝的原初始化fromDate数据*/
    this.tableParam = { ...this.tableParam, dataPeriods: "", CreateUserName: "" };
    this.gettableData();
    /**
     * @Description: 获取标号
     * @param {*}
     * @Author: wangwangwang
     */
    this.initCodeList();
  },
  methods: {
    /*重置数据,此方法必须存在，并且方发只重置条件*/
    init() {
      this.gettableData();
    },
    /**添加数据*/
    add(text) {
      this.addDialog = true;
      this.addDialogTitle = text;
      this.selectRow = "";
      this.fromDate = {
        dataYear: '',
        dataPeriods: '',
        time: [],
      }
      this.lineList = [];
      this.columnList = this.columnLists;
      this.nameArr.forEach((v, k) => {
        this.addline(v, k)
      })
    },
    /**修改数据*/
    update(low, text) {
      this.addDialog = true;
      this.addDialogTitle = text;
      this.selectRow = low;
      queryDetail({ id: low.id }).then(res => {
        if (res.code === 1001) {
          this.fromDate = {
            id: res.data.id,
            dataYear: res.data.dataYear,
            dataPeriods: res.data.dataPeriods,
            time: [res.data.startTime, res.data.endTime],
          }
          const columnList = [{
            itemName: 'itemCode',
            type: 1,
          }];
          const lineList = [];
          /**
           * @Description: 构造表头
           * @param {*} let
           * @Author: wangwangwang
           */
          for (let i = 0; i < res.data.tableLable.length; i += 1) {
            const data = {
              itemName: res.data.tableLable[i].itemCode,
              type: res.data.tableLable[i].itemName * 1,
              id: res.data.tableLable[i].id,
            }
            columnList.push(data);
          }
          this.columnList = columnList;
          /**
           * @Description: 构造数据
           * @param {*}
           * @Author: wangwangwang
           */
          for (let i = 0; i < this.nameArr.length; i += 1) {
            const data = {
              itemCode: this.nameArr[i],
              areaCode: i + 1,
            }
            for (let j = 0; j < res.data.valueList.length; j += 1) {
              if (res.data.valueList[j].areaCode == String(i + 1)) {
                data[res.data.valueList[j].lableId] = res.data.valueList[j].dataValue;
                data['itemName'] = res.data.valueList[j].dataValue;
              }
            }
            lineList.push(data);
          }
          this.lineList = lineList;
          console.log(JSON.parse(JSON.stringify(this.lineList)))
        }
      })
    },
    /**删除数据*/
    deldata(low) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'bottom_all_two',
        confirmButtonClass: 'bottom_all',
        type: 'warning'
      }).then(() => {
        deletePrice({ id: low.id, status: 0 }).then(res => {
          if (res.code == 1001) {
            this.gettableData();
          }
        })
      }).catch(() => {
      });
    },
    /**添加行*/
    addline(itemCode, k) {
      const data = {};
      for (let i = 0; i < this.columnList.length; i += 1) {
        data[this.columnList[i].itemName] = '';
        data['areaCode'] = k + 1;
      }
      data.itemCode = itemCode;
      this.lineList.push(data);
    },
    /**
     * @Description: 添加列
     * @param {*}
     * @Author: wangwangwang
     */
    addColume(type) {
      this.columnList.push({
        type,
        itemName: '',
      })
    },
    /**保存数据*/
    submit1() {
      if (!this.fromDate.dataYear || !this.fromDate.dataPeriods) {
        this.$message({
          showClose: true,
          message: '警告哦，请填写期数',
          type: 'warning'
        });
        return
      }
      if (!this.fromDate.time) {
        this.$message({
          showClose: true,
          message: '警告哦，请选择时间',
          type: 'warning'
        });
        return
      }
      const tableList = [];
      const valueList = [];
      for (let i = 0; i < this.columnList.length; i += 1) {
        if (this.columnList[i].itemName !== "itemCode") {
          const data = {
            itemCode: this.columnList[i].itemName,
            itemName: this.columnList[i].type,
            type: 1,
          }
          tableList.push(data);
        }
      }
      for (let i = 0; i < this.lineList.length; i += 1) {
        const List = this.lineList[i];
        const keysList = Object.keys(List);
        for (let j in keysList) {
          if (keysList[j] && keysList[j] !== 'itemCode' && keysList[j] !== 'areaCode') {
            const data = {
              areaCode: i + 1,
              lableId: keysList[j],
              dataValue: List[keysList[j]],
            }
            valueList.push(data);
          }
        }
      }
      let data = {
        ...this.fromDate,
        startTime: this.fromDate.time[0],
        endTime: this.fromDate.time[1],
        company: this.selectRow?.company || getUserInfo().companyName,
        companyId: this.selectRow?.companyId || getUserInfo().companyId,
        tableList,
        valueList,
      }
      const loading = this.$loading({})
      savePrice(data).then(res => {
        loading.close();
        if (res.code == 1001) {
          this.$message({
            message: '保存成功',
            type: 'success'
          });
          this.gettableData();
          this.addDialog = false
        }
      })
    },
    initCodeList() {
      getLists().then(res => {
        if (res.code === 1001) {
          const newData = res.data[0].list.filter(item => !this.defaultGrade.includes(item.name));
          this.gradeList = newData;
        }
      })
    },
    // changeArea(value, label, extra, index) {
    //   const areaCode = [extra.triggerNode.$parent.$parent.$options.propsData.value, extra.triggerNode.$parent.$options.propsData.value, value];
    //   const copyData = this.lineList.map((item, idx) => index === idx ? { ...item, areaCode } : { ...item });
    //   this.lineList = copyData;
    // },
    deleteRow(index) {
      this.lineList.splice(index, 1)
    },
    deleteColumn(index) {
      this.columnList.splice(index, 1)
    },
    TreeSelectStypeFun() {
      if (this.TreeSelectStypeNumber === 0) {
        this.TreeSelectStypeNumber = 1;
        setTimeout(() => {
          const dom = document.body.lastChild;
          dom.style.zIndex = '10000'
        }, 1000)
      }
    },
    sizeChange(value) {
      this.tableParam.pageSize = value;
      this.gettableData();
    },
  },
};
</script>

<style lang="scss" scoped>
.el-input,
.el-select {
  width: 240px;
}
.top {
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
<style lang="scss">
.priceMaintenance {
  .input1 {
    .el-input__inner {
      border-right: 0;
      border-top-right-radius: 0 !important;
      border-bottom-right-radius: 0 !important;
    }
  }
  .input2 {
    .el-input__inner {
      border-left: 0px;
      border-top-left-radius: 0 !important;
      border-bottom-left-radius: 0 !important;
    }
  }
  .xieXian {
    position: relative;
    height: 40px;
    overflow: hidden;
    > div:nth-of-type(1) {
      position: absolute;
      top: 45px;
      left: 0;
      transform: rotateZ(24deg);
      width: 208px;
      height: 1px;
      background: #c1c1c1;
    }
    > span:nth-of-type(1) {
      position: absolute;
      left: 0;
      top: 20px;
    }
    > span:nth-of-type(2) {
      position: absolute;
      left: 55px;
      top: 4px;
    }
  }
}
</style>

